package com.bingxue.edu.framework.mybatis.base;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ClassUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;

import java.io.Serializable;

/**
 * 通用业务抽象类
 *
 * @param <M> Mapper 接口
 * @param <T> 实体类型
 * @author panbo
 * @since 2024/6/28
 */
public abstract class BaseService<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {

    public M getMapper() {
        return this.mapper;
    }

    @SuppressWarnings("unchecked")
    protected final Class<T> entityClass = (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1);

//    @Override
//    public boolean create(Req req) {
//        T entity = BeanUtil.copyProperties(req, this.entityClass);
//        return save(entity);
//    }
//
//    @Override
//    public <C> boolean update(C req, Serializable id) {
//        T entity = this.getById(id);
//        BeanUtil.copyProperties(req, entity, CopyOptions.create().ignoreNullValue());
//        return updateById(entity);
//    }

    /**
     * 从请求对象中复制属性，并生成实体对象
     * @param req 请求对象
     * @return 实体对象
     */
    public T copy(Object req) {
        return BeanUtil.copyProperties(req, this.entityClass);
    }

    /**
     * 根据id查询实体对象，并从请求对象中复制属性到实体对象
     * @param req 请求对象
     * @return 实体对象
     */
    public T copyById(Object req, Serializable id) {
        T entity = this.getById(id);
        BeanUtil.copyProperties(req, entity, CopyOptions.create().ignoreNullValue());
        return entity;
    }

    public T copy(Object req, T entity) {
        BeanUtil.copyProperties(req, entity, CopyOptions.create().ignoreNullValue());
        return entity;
    }

}
